package com.platform.common.handler.exception;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * describe:
 * 策略模式+简单工厂模式
 * @author rainly
 * @date 2020/3/14
 * @time 9:31 下午
 */
public class ExceptionResultFactory {

    private ExceptionResultFactory() {

    }

    private static Map<Class<? extends Exception>, ExceptionResult> exceptionMap = new HashMap<>();

    private static SystemExceptionResult defaultExceptionResult = new SystemExceptionResult();

    //TODO 需要逐渐完善
    static {
        exceptionMap.put(NoHandlerFoundException.class,new NotFoundExceptionResult());
        exceptionMap.put(HttpRequestMethodNotSupportedException.class,new MethodNotSupportedExceptionResult());
        exceptionMap.put(HttpMediaTypeNotSupportedException.class,new MediaTypeNotSupportedExceptionResult());
        exceptionMap.put(HttpMediaTypeNotAcceptableException.class,new HttpMediaTypeNotAcceptableExceptionResult());
        exceptionMap.put(HttpMessageNotReadableException.class,new HttpMessageNotReadableExceptionResult());
    }

    public static ExceptionResult getResult(Exception ex) {
        ExceptionResult exceptionResult = exceptionMap.get(ex.getClass());
        if (null == exceptionResult) {
            return defaultExceptionResult;
        }
        return exceptionResult;
    }
}
